<script setup> 
import { ref } from 'vue'
import { LoginUser } from '../../api/login'
import { ElMessage } from 'element-plus'
//登陆成功后要跳转到首页
import router from '../../router/index'
//定义登录的表单数据
const loginForm = ref({username:'',password:''})

//引用表单
const ruleFormRef = ref(null)
//表单验证
const rules = ref({
  username: [
    { required: true, message: '账号不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在2-20个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '密码不能为空', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在2-30个字符', trigger: 'blur' },
  ]
})

//登录的点击事件，来发起登录请求
const login = () =>{
  // const result = await LoginUser(loginForm.value)
  //表单校验通过才会执行
  if (!ruleFormRef) return
  ruleFormRef.value.validate( async (valid, fields) => {
    if (valid) {
      //校验通过才会执行
      const result = await LoginUser(loginForm.value)
      if(result.code){
        localStorage.setItem('userToken',JSON.stringify(result.data))
        ElMessage.success('登陆成功')
        //登录成功要跳转到首页
        router.push('/index')
      }else{
        ElMessage.error('登陆失败！请重新登录')
      }
    } else {
      ElMessage.error('登录校验失败，请重新登录！')
    }
  })
}

//取消登录的点击事件
const clear =()=>{
  loginForm.value = {username:'',password:''}
  if (!ruleFormRef.value) return
  ruleFormRef.value.resetFields()
}
</script>

<template>
  <div class="login-container">
    <h3 class="login-title">登陆页面</h3>
    <div class="form-container">
      <el-form :rules="rules" ref="ruleFormRef" :model="loginForm" :hide-required-asterisk="true">
        <el-form-item label="账号" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入账号" clearable />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="loginForm.password" placeholder="请输入密码" clearable />
        </el-form-item>
        <div class="button-container">
          <el-form-item>
            <el-button type="primary" @click="login">登录</el-button>
            <el-button type="default" @click="clear">取消</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: url('@/assets/loginView.jpg') no-repeat center center;
  background-size: cover;
  position: relative;
}
.form-container {
  width: 300px;
}
.el-form-item {
  margin-bottom: 20px;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
}

.button-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style>